<?php
/*
Template Name: actions
*/
require_once(ABSPATH . WPINC . '/registration.php');
//print_r($_POST);
	if($_POST['action']=="sendmail")
	{
	  send_email();
	}
	if($_POST['action']=="register")
	{
	  register();
	}
	if($_POST['action']=="login")
	{
	  login();
	}
	if($_POST['action']=="forgotpass")
	{
	  forgot_password();
	  
	}
	if($_POST['action']=="logout")
	{
	 
		wp_logout();
		header("location: ".get_option("siteurl"));
	}
	//print_r($_POST);
function register()
{
	
	$user_id = username_exists( $_POST['username'] );
	$email_id =  email_exists($_POST['email']);
	if ( !$user_id ) {
		if(!$email_id)
		{
			$user_id = wp_create_user( $_POST['username'], $_POST['password'] , $_POST['email'] );
		}else{
			echo "มีอีเมล์นี้อยู่ในระบบแล้ว";
		}
		
		} else {
		echo 'ชื่อผู้ใช้งานนี้มีในระบบแล้วครับ';
	}
	
} 

function send_email()
{

	$name = $_POST['name1'];
	$email = $_POST['email'];
	$detail = $_POST['detail'];
	
	$message = $detail."  |--->[ชื่อ : $name ] -->[email: $email ]";
	$to  = get_option("admin_email");
	$subject = 'you have a contact from: ('.get_option("blogname").')';
	$headers = 'Content-type: text/html; charset=UTF-8;\r\n
	From: webmaster@example.com' . "\r\n" .
	'Reply-To:' .get_option('admin_email'). "\r\n";
	
	 if(mail($to, $subject, $message, $headers))
	 {
	 	echo "email is done!";
	 }
	
	
}	
	
function login(){
	

			$creds = array();
			$creds['user_login'] = $_POST["username"];
			$creds['user_password'] = $_POST["password"];
			$creds['remember'] = true;
			$user = wp_signon( $creds, false );
			if ( is_wp_error($user) ){
			   echo $user->get_error_message();
			
			}
			else
			{
				 header("location: ".get_option("siteurl"));
			}
	
	
	
}
function forgot_password()
{	
	
		$user_id =  email_exists($_POST['email']);
		print($user_id);
		if($user_id)
		{
		  $user = 	get_userdata($user_id);
		 //print_r($user);
		  	
			$message = $detail."<br/><br/>ชื่อ : $name <br/>  email: $email";
			$to  = $_POST['email'];
			$subject = 'รหัสผ่านใหม่ของคุณ: ('.get_option("blogname").')';
			$headers = 'Content-type: text/html; charset=UTF-8;\r\n
			From: '.get_option('admin_email') . "\r\n" .
			'Reply-To:' .get_option('admin_email'). "\r\n";
				$random_password = wp_generate_password( 12, false );
				$obj = array("user_pass" =>$random_password,"ID"=>$user_id);
				wp_update_user( $obj ); 
			 $message ='username:'.$user->user_login.'<br/>Password:'.$random_password."<br/>".get_option("siteurl");
		
			
			// echo $message;
				if(mail($to, $subject, $message, $headers))
			 {
			 	echo "sended new password to  your email!";
			 }
			
		}
		else
		{
			
			echo "ไม่มีอีเมล์นี้อยู่ในระบบ";
		}
	
}

?>